<template>
  <div class="big-box">
    <div class="content">
      <div class="head-portrait">
        <a-card style="width: 100%" class="cord-user">
          <div class="user-card">
            <div class="top">

              <div class="ava">
                <van-uploader :after-read="afterRead"
                              :max-count="1"
                              :max-size=" 5 * 1024 * 1024"
                              @oversize="onOversize">
                  <div>
                    <van-image
                        :alt="userInfos?.username"
                        class="img"
                        :src="userInfos?.avatarUrl ? userInfos?.avatarUrl :defaultPic "
                    />
                  </div>
                </van-uploader>
              </div>
              <div class="user-info">
                <div class="username">
                  {{ userInfos?.username }}
                </div>
                <div class="profile">
                  <EditOutlined/>
                  {{ userInfos?.profile }}
                </div>
              </div>

            </div>

            <div class="bom">
              <div class="tag">
                <TagsOutlined style="margin-right: 8px"/>
                <a-tag color="blue" :bordered="false" class="new-tag">
                  <template #icon v-if="userInfos?.gender===0">
                    <WomanOutlined/>
                    女生
                  </template>
                  <template #icon v-else>
                    <ManOutlined/>
                    男生
                  </template>
                </a-tag>
                <a-tag color="#70b5ff" :bordered="false" v-for="item in tag" class="new-tag">{{
                    item
                  }}
                </a-tag>

              </div>
              <div class="join-time">
                加入青青同行：
                {{ joinDays }}天了
                <smile-two-tone two-tone-color="#eb2f96"/>
              </div>
            </div>
          </div>
        </a-card>
      </div>
      <div class="Information">
        <van-cell title="我加入的队伍" icon="friends" is-link to="/user/team/join">
          <!-- 使用 right-icon 插槽来自定义右侧图标 -->
          <template #right-icon>
            <van-icon name="arrow" class="cell-icon"/>
          </template>
        </van-cell>
        <van-cell title="队伍管理" is-link to="/user/team/create">
          <template #title>
            <div class="left-icon">
              <AppstoreFilled/>
            </div>
            <span class="custom-title">队伍管理</span>
          </template>
          <!-- 使用 right-icon 插槽来自定义右侧图标 -->
          <template #right-icon>
            <van-icon name="arrow" class="cell-icon"/>
          </template>
        </van-cell>

        <van-cell title="标签修改"  is-link @click="tagUpdate('tags','我的标签',userInfos.tags)">
          <!-- 使用 right-icon 插槽来自定义右侧图标 -->
          <template #title>
            <div class="left-icon">
              <TagsFilled/>
            </div>
            <span class="custom-title">
             <span class="tit_a">标签修改</span>
            </span>
          </template>
          <template #right-icon>
            <van-icon name="arrow" class="cell-icon"/>
          </template>
        </van-cell>
        <van-cell title="修改信息" is-link to="/user/update" icon="manager">
          <!-- 使用 right-icon 插槽来自定义右侧图标 -->
          <template #right-icon>
            <van-icon name="arrow" class="cell-icon"/>
          </template>
        </van-cell>
        <van-cell title="设置" icon="setting">
          <!-- 使用 right-icon 插槽来自定义右侧图标 -->
          <template #right-icon>
            <van-icon name="arrow" class="cell-icon"/>
          </template>
        </van-cell>
        <van-cell title="退出登录" class="custom-title" @click="userLogout">
          <!-- 使用 right-icon 插槽来自定义右侧图标 -->
          <template #title>
            <div class="left-icon">
              <RightCircleFilled/>
            </div>
            <span class="custom-title">退出登录</span>
          </template>

          <template #right-icon>
            <van-icon name="arrow" class="cell-icon"/>
          </template>
        </van-cell>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
// import useUserStore from "../pinia/userStore.js";
// import {storeToRefs} from "pinia";
import {showConfirmDialog, showFailToast, showNotify, showSuccessToast} from "vant";
// import {logout} from "../service/userapi.js";
import {useRouter} from "vue-router";
import {
  AppstoreFilled,
  EditOutlined,
  ManOutlined,
  RightCircleFilled,
  SmileTwoTone,
  TagsFilled,
  TagsOutlined,
  WomanOutlined
} from "@ant-design/icons-vue"
import dayjs from "dayjs";
import {dateDiffInDays} from "../utils/myDayUtils.js";
import {onMounted, ref} from "vue";
import myAxios from "../plugins/myAxios.ts";
import {getCurrentUser} from "../services/user.ts";
import {UserType} from "@/models/user";


const userInfos = ref<UserType>();
const show_UserAvatarUrl_pop = ref("true")
let tag;
// 加入时间
let joinTime;
let joinDays;

onMounted(async ()=>{

  //获取用户信息
  //const res = await myAxios.get('/user/current');
  // 异步方法必须添加await才可以拿到数据，否则拿到的是promise对象
  const  res = await getCurrentUser();
  userInfos.value =res;
  if(res.data){
    const show_updateUserAvatarUrl = sessionStorage.getItem("userAvatarUrl")
    show_UserAvatarUrl_pop.value = show_updateUserAvatarUrl ? show_updateUserAvatarUrl : show_UserAvatarUrl_pop.value
    if (show_UserAvatarUrl_pop.value === "true") {
      showNotify({message: '点击头像可更换默认头像', type: "primary", duration: 2000});
      show_UserAvatarUrl_pop.value = "false"
      sessionStorage.setItem('userAvatarUrl', show_UserAvatarUrl_pop.value)
    }
  }

  tag = userInfos.value.tags;
  if(tag !==undefined){
    tag = JSON.parse(tag);
  }

  // 加入时间
  joinTime = userInfos.value.createTime
  joinDays = dateDiffInDays(dayjs(joinTime).$d, new Date())

})

// let tag = userInfos.value.tags;
// if(tag !==undefined){
//   tag = JSON.parse(tag);
// }

// userInfos.value = user.value;

const router = useRouter()
const userLogout = () => {
  // dialog 对话弹窗
  showConfirmDialog({
    title: '退出登录',
    message:
        '确认要退出登录吗？',
  })
      .then(() => {
        const loginOut = myAxios.post("/user/logout", {})
        if (loginOut) {
          showSuccessToast("退出成功")
          router.replace("/user/login").catch(e => console.log(e))
        }
        // const loginOut = async () => {
        //   const loginOut = await myAxios.post("/user/logout", {})
        //   if (loginOut) {
        //     showSuccessToast("退出成功")
        //     router.replace("/user/login").catch(e => console.log(e))
        //   }
        // }

        // logout();
        // router.push("/login")
        // on confirm
      })
      .catch(() => {
        // on cancel
      });
};

const updateAvatarUrl = ref(false)
const afterRead = async (file: any) => {
  updateAvatarUrl.value = true
  if (updateAvatarUrl.value) {
    const fileFile = file.file
    const res = await myAxios.post("/file/upload", {
      'file': fileFile,
      'biz': "user_avatar"
    }, {
      headers: {'Content-Type': 'multipart/form-data'},
    })
    const updateUserAvatarUrl = await myAxios.post("/user/update", {
      id: userInfos.value.id,
      avatarUrl: res.data
    })
    console.log("res.data"+ res.data)
    if (updateUserAvatarUrl) {
      userInfos.value = await getCurrentUser()
      showSuccessToast("更新成功")
      setTimeout(() => {
        updateAvatarUrl.value = false
      }, 1000);
    }
  }
}

const onOversize = () => {
  showFailToast("头像上传大小不能超过5mb")
}

const tagUpdate = (editKey: string, editName: string, currentValue) => {
  router.push({
    path: "/updateTags",
    query: {
      editKey,
      editName,
      currentValue,
      // id: id,
      // tags: JSON.parse(tags),
    }
  })
}

// 调至更新信息
const toUpdate = ()=>{
  router.push("/user/update");
}
const defaultPic ="https://bucket-ss.oss-cn-hangzhou.aliyuncs.com/index_background/01fec958158d43a84a0d304fc3c541.png"
</script>

<style scoped>
.big-box {
  width: 100%;
  height: 100%;
}

.content {
  position: relative;
}

.top {
  display: flex;
  align-items: center;
}

.cord-user {
  position: relative;
  top: 35px;
}

.head-portrait {
  display: flex;
  flex-direction: column;
  padding: 0 20px;
  /*width: 100%;*/
  /*background: url(../assets/image/uername.jpg);*/
  background: url(../assets/background.jpg);
  background-size: cover;
}

.join-time {
  margin-top: 4px;
  font-size: 12px;
  color: #555;
}

.ava {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  border: solid 2px pink;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.ava img {
  width: 100%;
  height: 100%; /* 让高度自动调整，保持宽高比例 */
  object-fit: fill; /* 图像将被拉伸以填充容器 */
}

.user-info {
  margin-left: 20px;
}

.username {
  font-size: 24px;
  font-weight: 700;
  margin: 4px 0;
}

.profile {
  color: #999;
  margin: 5px 0;
}
.updateInfo-btn{
  flex: 1;
  text-align: right;
  vertical-align: middle;
  color: #4096ff;
}
.tag {
  padding: 4px;
}

.new-tag {
  margin:4px;
}

.Information {
  display: flex;
  height: 100%;
  flex-direction: column;
  justify-content: space-between;
  padding-top: 50px;
}

.join-time {
  width: 100%;
  text-align: right;
  margin-top: 6px;
}

.custom-title {
  margin-right: 4px;
  vertical-align: middle;
}

.cell-icon {
  font-size: 16px;
  line-height: inherit;
}

.left-icon {
  display: inline-block;
  margin-right: 6px;
  vertical-align: middle;
  padding-bottom: 2px;
}

:deep(.van-cell__title span) {
  vertical-align: middle;
}

:deep(.ant-card-body) {
  padding: 20px 20px 10px 20px !important;
}
:deep(.ant-btn-default){
  color: #009ef7;
  border-color:#009ef7;
}
.tit_a{
  color: var(--van-cell-text-color);
}
</style>




